package com.ywjt.platformbusiness.login;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.common.MethodUtils;
import com.ywjt.platformbusiness.common.UserData;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.login.model.LoginModel;
import com.ywjt.platformbusiness.main.MainActivity;
import com.ywjt.platformbusiness.my.activity.ActivitySet;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.SPUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity  extends BaseActivity implements View.OnClickListener {

    private LinearLayout llGoToRegister;
    private EditText etAccount,etPassword;
    private TextView tvLogin,tvForgetPwd;
    private ImageView ivAgree;
    private Boolean isAgree=false;

    private String account="";//账号
    private String password="";//密码

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llGoToRegister:
                RegisterActivity.actionStart(this);
                break;
            case R.id.tvLogin:
                if (isAgree){
                    login();
                }else {
                    Toast.makeText(this,"您必须同意该App相关协议以继续更好使用",Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case R.id.tvForgetPwd:
                //忘记密码
                ResetPwdActivity.actionStart(this);
                break;
            case R.id.ivAgree:
                if (isAgree){

                    ivAgree.setImageResource(R.mipmap.icon_login_unselected);
                }else {
                    ivAgree.setImageResource(R.mipmap.icon_login_selected);
                }
                isAgree=!isAgree;
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        etPassword=findViewById(R.id.etPassword);
        llGoToRegister=findViewById(R.id.llGoToRegister);
        tvLogin=findViewById(R.id.tvLogin);
        etAccount=findViewById(R.id.etAccount);
        tvForgetPwd=findViewById(R.id.tvForgetPwd);
        ivAgree=findViewById(R.id.ivAgree);
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                password=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                account=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        llGoToRegister.setOnClickListener(this::onClick);
        tvLogin.setOnClickListener(this::onClick);
        tvForgetPwd.setOnClickListener(this::onClick);
        ivAgree.setOnClickListener(this::onClick);
    }

    /**
     * 登录
     */
    private void login() {
        if(account==null||account.equals("")){
            Toast.makeText(getContext(),"请填写手机号码",Toast.LENGTH_SHORT).show();
            return;
        }
        if(password==null||password.equals("")){
            Toast.makeText(getContext(),"请填写密码",Toast.LENGTH_SHORT).show();
            return;
        }
        Map map = new HashMap<>();
        map.put("account", account);
        map.put("password", password);

        new HttpRequest(getContext()).doPost(UrlConstants.login_loginP, "登录中", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), LoginModel.class);
                        if (obj instanceof LoginModel) {
                            LoginModel model = (LoginModel) obj;
                            MethodUtils.loginAfter(LoginActivity.this, model.getResult().getUserMessage().getId(),
                                    model.getResult().getToken());
                            UserData.create(LoginActivity.this).saveUserData(model.getResult().getUserMessage());
                            MainActivity.actionStart(LoginActivity.this,0);
                         SPUtils.setSharedBooleanData(LoginActivity.this,"isLogin",true);
                            }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }
}
